package ace.cmp.data.methodname.sql.mybatisplus.core.util;

import ace.cmp.data.methodname.method.name.sql.core.util.StringUtils;
import ace.cmp.data.methodname.method.name.sql.entity.model.EntityMapping;
import ace.cmp.data.methodname.method.name.sql.entity.model.EntityPropertyMapping;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author caspar
 * @date 2023/2/24 15:24
 */
public final class EntityMappingUtils {
  public static EntityMapping getEntityMappingByClass(Class cls) {
    TableInfo tableInfo = TableInfoHelper.getTableInfo(cls);
    return getEntityMapping(tableInfo);
  }

  public static EntityMapping getEntityMapping(TableInfo tableInfo) {
    EntityMapping entityMapping =
        EntityMapping.builder()
            .tableName(tableInfo.getTableName())
            .entityClass(tableInfo.getEntityType())
            .properties(getEntityPropertyMappings(tableInfo))
            .build();

    return entityMapping;
  }

  public static List<EntityPropertyMapping> getEntityPropertyMappings(TableInfo tableInfo) {
    List<EntityPropertyMapping> propertyMappings =
        tableInfo.getFieldList().stream()
            .map(
                filed -> {
                  Boolean propertyIsId = filed.getProperty().equals(tableInfo.getKeyProperty());
                  String propertyPathMeta = StringUtils.toUpperCaseFirstOne(filed.getProperty());
                  EntityPropertyMapping propertyMapping =
                      EntityPropertyMapping.builder()
                          .column(filed.getColumn())
                          .property(filed.getProperty())
                          .propertyClass(filed.getPropertyType())
                          .propertyIsId(propertyIsId)
                          .propertyPathMeta(propertyPathMeta)
                          .build();
                  return propertyMapping;
                })
            .collect(Collectors.toList());
    if (StringUtils.isEmpty(tableInfo.getKeyProperty()) == false) {
      String propertyPathMeta = StringUtils.toUpperCaseFirstOne(tableInfo.getKeyProperty());
      propertyMappings.add(
          0,
          EntityPropertyMapping.builder()
              .column(tableInfo.getKeyColumn())
              .property(tableInfo.getKeyProperty())
              .propertyClass(tableInfo.getKeyType())
              .propertyIsId(true)
              .propertyPathMeta(propertyPathMeta)
              .build());
    }
    return propertyMappings;
  }
}
